﻿/// <Summary> 
/// $Author: Nikhil Chinchwade 
/// This class provides a mechanism to retrieve the current GMT time.  This class communicates to http://www.timeanddate.com/worldclock
/// to retrieve the current GMT time.

/// $Creation Date : 
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace MindTree.PerfWorkbench.Azure.Monitor.AzureMonLib
{
    /// <summary>
    /// This class provides a mechanism to retrieve the current GMT from web portal http://www.timeanddate.com
    /// </summary>
    public class WebTimeClient
    {

        /// <summary>
        /// Static method to retrieve current GMT
        /// </summary>
        /// <returns>Current GMT in DateTime Format</returns>
        public static DateTime GetCurrentGMT()
        {
            string URL = "http://www.timeanddate.com/worldclock";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            HttpWebResponse respons;

            respons = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(respons.GetResponseStream());
            string sr = reader.ReadToEnd();

            //string Pattern = "<strong.*?id=['\"]ctu['\"].*?>(?<time>[^<]*)<";
            string Pattern = "<strong.*id=ctu>(?<time>.*)</strong>";
            string val = Regex.Matches(sr, Pattern, RegexOptions.IgnoreCase)[0].Groups["time"].Value;
            DateTime CurrentGMT ;
            try
            {
                CurrentGMT = DateTime.Parse(val);
            }
            catch (Exception ex)
            {
                return DateTime.UtcNow;
            }
            return CurrentGMT;
        }    
    }
}
